package com.GlobalPaint.app.ui.Home.friend;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.HaoyouShuJuBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.UiUtil;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.baidu.mapapi.BMapManager.getContext;
import static org.jivesoftware.smackx.pubsub.FormType.result;

public class QunLiaoWzhiActivity extends AppCompatActivity implements
        OnGetGeoCoderResultListener {
    @BindView(R.id.iv_goback)
    ImageView ivGoback;
    @BindView(R.id.tv_common_center)
    TextView tvCommonCenter;
    @BindView(R.id.bmapView)
    MapView bmapView;
    private BaiduMap map;
    private LatLng dxu;
    private View popView;
    private double centWd;
    private double centJd;
    private HaoyouShuJuBean bean;
    private TextView tv_title;
    private String Roomname;
    GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private TextView tv_title1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qun_liao_wzhi);
        ButterKnife.bind(this);
        tvCommonCenter.setText("好友位置");
        popView = View.inflate(getContext(), R.layout.pop_view1, null);
        Roomname=getIntent().getStringExtra("Roomname");
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        initBaiduMap();//初始化百度地图
        getShuju();
    }
    private void getShuju() {
        String url = Constants.JASON_SERVICE_URL + "qlxroomuserrelation/querygisByroom?roomName="+Roomname;
        DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), HaoyouShuJuBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                bean=(HaoyouShuJuBean)o;
                if (bean.getStatus()==1){
                    if(bean.getData().size()>0){
                        if(bean.getData().get(0)!=null){
                            //设置第一个为中点
                            dxu = new LatLng(bean.getData().get(0).getLat(), bean.getData().get(0).getLng());
                            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(dxu);
                            map.setMapStatus(update);
                            update = MapStatusUpdateFactory.zoomBy((3));
                            map.setMapStatus(update);
                            initMarket();    //标志
                            initPopView();  //初始化pop
                        }
                    }

                }

            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {

            }
        });
    }

    private void initBaiduMap() {
        bmapView.showScaleControl(false);
        map = bmapView.getMap();

        map.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            /**
             * 当用户触摸地图时回调函数
             * @param event 触摸事件
             */
            public void onTouch(MotionEvent event) {
                map.hideInfoWindow();//隐藏消息窗
                popView.setVisibility(View.GONE);
            }
        });
    }
    /**
     *初始化地图
     */
    private void initMarket() {
        for (int i = 0; i < bean.getData().size(); i++) {
            View inflate = View.inflate(getApplicationContext(), R.layout.point, null);
            TextView dtTv = (TextView) inflate.findViewById(R.id.ditu_text);
            dtTv.setText(bean.getData().get(i).getRealName()==null?bean.getData().get(i).getUserName():bean.getData().get(i).getRealName());
            Bitmap viewBitmap = getViewBitmap(inflate);
            BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(viewBitmap);
            MarkerOptions options = new MarkerOptions();

            options.position(new LatLng(bean.getData().get(i).getLat(), bean.getData().get(i).getLng()))
                    .icon(descriptor)
                    .draggable(true)
                    .title(String.valueOf(i));
            map.addOverlay(options);
        }
    }
    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }
    private void initPopView() {
        // popView = View.inflate(getContext(), R.layout.pop_view1, null);
        popView.setVisibility(View.GONE);
        tv_title = (TextView) popView.findViewById(R.id.tv_title);
        tv_title1 = (TextView)popView. findViewById(R.id.tv_title1);
        if (popView.getParent() == null)
            bmapView.addView(popView, createLayoutParams(dxu));

        map.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                updatePopView(marker);
                return true;
            }
        });
    }
    private void updatePopView(final Marker marker) {
        bmapView.updateViewLayout(popView, createLayoutParams(marker.getPosition()));
        popView.setVisibility(View.VISIBLE);
        final int id = Integer.parseInt(marker.getTitle());
        centWd=bean.getData().get(id).getLat();
        centJd=bean.getData().get(id).getLng();
        LatLng ptCenter = new LatLng(centWd,centJd);
        // 反Geo搜索
        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(ptCenter));
        tv_title.setText(bean.getData().get(id).getUploadtime());
    }

    private MapViewLayoutParams createLayoutParams(LatLng xzPos) {
        MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)    // 坐标类型为经纬度的类型
                .position(xzPos)    // 指定View的位置
                .yOffset(UiUtil.dp2px(-38))       // 指定View在y方向的偏移量
                .build();
        return params;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        bmapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        bmapView.onPause();
    }

    @OnClick(R.id.iv_goback)
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.iv_goback:
                finish();
                break;
        }
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (result == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(QunLiaoWzhiActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (result == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(QunLiaoWzhiActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }else {
            tv_title1.setText(reverseGeoCodeResult.getAddress());    // 显示标志的标题
        }
    }
}
